<template>
  <div class="debug-page">
    <el-card>
      <template #header>
        <h2>🔍 认证状态诊断</h2>
      </template>
      
      <div class="debug-section">
        <h3>Token 信息</h3>
        <p><strong>Token存在:</strong> {{ hasToken ? '✅ 是' : '❌ 否' }}</p>
        <p v-if="hasToken"><strong>Token:</strong> <code>{{ tokenPreview }}</code></p>
        <p v-if="tokenPayload"><strong>用户ID:</strong> {{ tokenPayload.sub }}</p>
        <p v-if="tokenPayload"><strong>用户名:</strong> {{ tokenPayload.username }}</p>
        <p v-if="tokenPayload"><strong>是否游客:</strong> {{ tokenPayload.is_guest }}</p>
        <p v-if="tokenPayload"><strong>过期时间:</strong> {{ expireTime }}</p>
        <p v-if="tokenPayload"><strong>是否过期:</strong> {{ isExpired ? '⚠️ 是' : '✅ 否' }}</p>
      </div>
      
      <div class="debug-section">
        <h3>API 测试</h3>
        <el-button @click="testMe" :loading="testing.me">测试 /api/auth/me</el-button>
        <el-button @click="testExplore" :loading="testing.explore">测试 /api/explore/user/summary</el-button>
        <div v-if="apiResults.me" class="result-box">
          <h4>/api/auth/me 响应:</h4>
          <pre>{{ JSON.stringify(apiResults.me, null, 2) }}</pre>
        </div>
        <div v-if="apiResults.explore" class="result-box">
          <h4>/api/explore/user/summary 响应:</h4>
          <pre>{{ JSON.stringify(apiResults.explore, null, 2) }}</pre>
        </div>
      </div>
      
      <div class="debug-section">
        <h3>操作</h3>
        <el-button type="danger" @click="clearToken">清除 Token</el-button>
        <el-button @click="$router.push('/')">返回首页</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { getToken, removeToken } from '@/utils/auth'
import { authApi } from '@/api/http'
import { exploreApi } from '@/api/explore'
import { ElMessage } from 'element-plus'

const token = ref(null)
const tokenPayload = ref(null)
const apiResults = ref({ me: null, explore: null })
const testing = ref({ me: false, explore: false })

const hasToken = computed(() => !!token.value)
const tokenPreview = computed(() => token.value ? `${token.value.substring(0, 50)}...` : '')
const expireTime = computed(() => {
  if (!tokenPayload.value?.exp) return '未知'
  return new Date(tokenPayload.value.exp * 1000).toLocaleString('zh-CN')
})
const isExpired = computed(() => {
  if (!tokenPayload.value?.exp) return false
  return Date.now() > tokenPayload.value.exp * 1000
})

onMounted(() => {
  token.value = getToken()
  if (token.value) {
    try {
      // 解码JWT payload
      const parts = token.value.split('.')
      if (parts.length === 3) {
        const payload = JSON.parse(atob(parts[1]))
        tokenPayload.value = payload
      }
    } catch (err) {
      console.error('Token解码失败:', err)
    }
  }
})

const testMe = async () => {
  testing.value.me = true
  try {
    const response = await authApi.me()
    apiResults.value.me = response.data
    ElMessage.success('API调用成功')
  } catch (err) {
    apiResults.value.me = { error: err.response?.data || err.message }
    ElMessage.error('API调用失败')
  } finally {
    testing.value.me = false
  }
}

const testExplore = async () => {
  testing.value.explore = true
  try {
    const response = await exploreApi.userSummary()
    apiResults.value.explore = response.data
    ElMessage.success('API调用成功')
  } catch (err) {
    apiResults.value.explore = { error: err.response?.data || err.message }
    ElMessage.error('API调用失败')
  } finally {
    testing.value.explore = false
  }
}

const clearToken = () => {
  removeToken()
  ElMessage.success('Token已清除，请重新登录')
  setTimeout(() => location.reload(), 1000)
}
</script>

<style scoped>
.debug-page {
  max-width: 900px;
  margin: 40px auto;
  padding: 20px;
}

.debug-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f5f5f5;
  border-radius: 8px;
}

.debug-section h3 {
  margin-top: 0;
  color: #c8102e;
}

.debug-section p {
  margin: 8px 0;
}

code {
  background: #fff;
  padding: 4px 8px;
  border-radius: 4px;
  font-family: monospace;
  font-size: 12px;
}

.result-box {
  margin-top: 16px;
  background: #fff;
  padding: 16px;
  border-radius: 8px;
  border: 1px solid #ddd;
}

.result-box h4 {
  margin-top: 0;
}

pre {
  background: #f9f9f9;
  padding: 12px;
  border-radius: 4px;
  overflow-x: auto;
  font-size: 12px;
}
</style>
